package com.duan.common.utils;

import com.auth0.jwt.interfaces.Claim;
import com.duan.common.beans.vo.SessionModel;
import com.duan.common.beans.vo.SessionUserModel;
import com.duan.common.enums.ResponseENUM;
import com.duan.common.exceptions.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by duanlsh on 18/9/16.
 */
public class SessionUtil {

    public static long sessionTimeOut = 30 * 60 * 1000;

    private static Logger logger = LoggerFactory.getLogger(SessionUtil.class);

    //K token V usermessage
    private static Map<String, SessionModel> sessionMap = new ConcurrentHashMap<>(20);

    public static Map<String, SessionModel> getSessionMap(){
        return sessionMap;
    }


    public static String createUserSession(Integer id, String loginName, String nickName, String phone, String departmentName, String email) {
        String token = null;
        try {
//            SessionUserModel sessionUserModel = new SessionUserModel();
//            sessionUserModel.setId(id);
//            sessionUserModel.setLoginName(loginName);
//            sessionUserModel.set

            SessionModel sessionModel = new SessionModel();
            sessionModel.setTokenCreateTime(System.currentTimeMillis());
            sessionModel.setId(id);
            sessionModel.setLoginName(loginName);

            sessionMap.put(token = JwtUtil.createToken(JsonUtil.objectToString(sessionModel)), sessionModel);
        } catch (Exception e) {
            throw new ServiceException("创建用户session失败");
        }
        return token;
    }

    public static void updateSessionTokenTime(String token) {
        SessionModel sessionModel = getUserSession(token);
        sessionModel.setTokenCreateTime(System.currentTimeMillis());
    }


    public static SessionModel getUserSession(String token) {
        SessionModel sessionModel = null;
        try {
            JwtUtil.verifyToken(token);
            sessionModel = sessionMap.get(token);
            if (sessionModel == null) {
                throw new ServiceException(ResponseENUM.FAIL_TOKEN.getCode(), "session不存在，请重新登陆");
            }
            if ((System.currentTimeMillis() - sessionModel.getTokenCreateTime()) > sessionTimeOut) {
                sessionMap.remove(token);
                throw new ServiceException(ResponseENUM.FAIL_TOKEN.getCode(), "session已经过期请重新登陆");
            }
        } catch (Exception e) {
            throw new ServiceException(ResponseENUM.FAIL_TOKEN.getCode(), "验证token失败");
        }
        return sessionModel;
    }


    public static void deleteUserSession(String token) {
        sessionMap.remove(token);
    }
}
